<template>
  <div class="project-manager">
    <!-- 操作栏 -->
    <div class="toolbar">
      <button @click="createNewProject">新建</button>
      <input v-model="searchQuery" placeholder="搜索项目..." />
      <select v-model="sortBy">
        <option value="updatedAt">修改时间</option>
        <option value="name">名称</option>
      </select>
    </div>

    <!-- 项目列表 -->
    <div class="project-grid">
      <div 
        v-for="project in filteredProjects"
        :key="project.id"
        class="project-card"
        @click="openProject(project)"
      >
        <div class="preview">{{ getPreviewText(project) }}</div>
        <div class="meta">
          <h3>{{ project.name }}</h3>
          <p>最后修改: {{ formatDate(project.updatedAt) }}</p>
        </div>
        <div class="actions">
          <button @click.stop="exportProject(project)">导出</button>
          <button @click.stop="deleteProject(project)">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { StorageService } from '@/services/storageService';
import { useRouter } from 'vue-router';

const router = useRouter();

// 响应式状态
const projects = ref(StorageService.getProjects());
const searchQuery = ref('');
const sortBy = ref('updatedAt');

// 计算属性
const filteredProjects = computed(() => {
  return projects.value
    .filter(p => p.name.includes(searchQuery.value))
    .sort((a, b) => b[sortBy.value] - a[sortBy.value]);
});

// 操作方法
const createNewProject = () => {
  const newProject = StorageService.saveProject({
    name: '未命名项目',
    data: { bars: [], lyrics: [] }
  });
  projects.value = StorageService.getProjects();
  openProject(newProject);
};

const openProject = (project) => {
  router.push(`/editor/${project.id}`);
};

const exportProject = async (project) => {
  try {
    await StorageService.exportProject(project.id);
    alert('导出成功！');
  } catch (error) {
    alert(`导出失败: ${error.message}`);
  }
};

const deleteProject = (project) => {
  if (confirm('确定删除此项目？')) {
    StorageService.deleteProject(project.id);
    projects.value = StorageService.getProjects();
  }
};

// 工具方法
const formatDate = (isoString) => {
  return new Date(isoString).toLocaleDateString();
};

const getPreviewText = (project) => {
  return project.data.bars
    .flat()
    .slice(0, 20)
    .join(' ');
};
</script>

<style scoped>
.project-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1rem;
}

.project-card {
  border: 1px solid #ccc;
  padding: 1rem;
  cursor: pointer;
  transition: transform 0.2s;
}

.project-card:hover {
  transform: translateY(-2px);
}

.preview {
  height: 100px;
  overflow: hidden;
}

.actions {
  display: flex;
  gap: 0.5rem;
  margin-top: 1rem;
}
</style>